/*
 * Created on 2004-05-26
 */
package org.opencube.oms.mapping.generator;

import java.util.ArrayList;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author <a href="mailto:maciek@fingo.pl">FINGO - Maciej Mroczko</a>
 * TODO: comment
 */
class XMIElement
{
	public static final String ATT_ID = "xmi.id";
	public static final String ATT_NAME = "name";
	
	protected Node node = null;
	
	public XMIElement( Node node )
	{
		this.node = node;
	}
	
	public String getId()
	{
		Node n = node.getAttributes().getNamedItem( ATT_ID );
		return n == null ? null : n.getNodeValue();
	}
	
	public String getName()
	{
		Node n = node.getAttributes().getNamedItem( ATT_NAME );
		return n == null ? null : n.getNodeValue();
	}
	
	public Node[] getFromFirstLevel( String name, String stopOn )
	{
		ArrayList list = getChildren( node, name, stopOn );
		return (Node[]) list.toArray( new Node[ list.size() ] );
	}
	
	public Node getByAttribute( String name, String stopOn, String attName, String attVal )
	{
		ArrayList list = getChildren( node, name, stopOn );
		for( int i = 0; i < list.size(); i++ )
		{
			Node n = (Node) list.get( i );
			NamedNodeMap nm = n.getAttributes();
			Node att = nm.getNamedItem( attName );
			if( att != null && ( attVal == null || att.getNodeValue().equals( attVal ) ) )
			{
				return n;
			}
		}
		return null;
	}
	
	private ArrayList getChildren( Node node, String name, String stopOn )
	{
		ArrayList result = new ArrayList();
		NodeList list = node.getChildNodes();
		boolean stopped = false;
		for( int i = 0; i < list.getLength(); i++ )
		{
			if( name.equals( list.item( i ).getNodeName() ) )
			{
				result.add( list.item( i ) );	
			}
			else if( list.item( i ).getNodeName().equals( stopOn ) )
			{
				stopped = true;
			}
			
		}
		if( result.size() == 0 && !stopped )
		{
			for( int i = 0; i < list.getLength(); i++ )
			{
				result.addAll( getChildren( list.item( i ), name, stopOn ) );	
			}
		}
		
		return result;
	}
	
	private String getValue( String attName )
	{
		return node.getAttributes().getNamedItem( attName ).getNodeValue();
	}
}
